﻿#include "analyzingconfig.h"
#include "ui_analyzingconfig.h"

extern intListener doorStatus;

//获取CheckBox
QCheckBox* AnalyzingConfig::getCheckBox(QTableWidget*table,int row ,int column)
{
    QWidget* pWidget = 0;
    pWidget = table->cellWidget(row,column); //找到单元格
    QCheckBox *pCheckBox = 0;
    bool bNew = true;
    if(pWidget != 0) //
    {
        bNew = false;
    }
    if(bNew)
    {
        pWidget = new QWidget(table); //创建一个widget
        QHBoxLayout *hLayout = new QHBoxLayout(pWidget); //创建布局
        pCheckBox = new QCheckBox(pWidget);
        //根据objectName ,去拆解所属的tableWidget 、行、列
        pCheckBox->setObjectName(QString("%1_%2_%3_Item").arg(table->objectName()).arg(row).arg(column));
        pCheckBox->setChecked(false);
        pCheckBox->setFont(table->font());
        pCheckBox->setFocusPolicy(Qt::NoFocus);
        pCheckBox->setStyle(QStyleFactory::create("fusion"));
        pCheckBox->setStyleSheet(QString(".QCheckBox {margin:3px;border:0px;}QCheckBox::indicator {width: %1px; height: %1px; }").arg(20));
        hLayout->addWidget(pCheckBox); //添加
        hLayout->setMargin(0); //设置边缘距离
        hLayout->setAlignment(pCheckBox, Qt::AlignCenter); //居中
        hLayout->setSpacing(0);
        pWidget->setLayout(hLayout); //设置widget的布局
        table->setCellWidget(row,column,pWidget);
    }
    QList<QCheckBox *> allCheckBoxs =  pWidget->findChildren<QCheckBox *>();
    allCheckBoxsval.append(pCheckBox);
    if(allCheckBoxs.size() > 0)
        pCheckBox = allCheckBoxs.first();
    return pCheckBox;
}

//处理CheckBox
QCheckBox* AnalyzingConfig::setCheckBox(QTableWidget*table,int row ,int column,bool checkd)
{
    QCheckBox *check = getCheckBox(table,row,column);

    if(check != 0) //
    {
        check->setChecked(checkd);
    }
    QCheckBox::connect(check,&QCheckBox::stateChanged,[=]{
        QString objectName = check->objectName();
        QStringList nameList = objectName.split("_");//拆解
        if(nameList.count() == 4)
        {
            int row = nameList.at(1).toInt();//行
            bool checked = check->isChecked();//是否被选中

            if(checked){
                QString id = ui->tableWidget->item(row,1)->text();//取出当前行第1列内容
                checkedInfo.append(id);
            }else{
                QString id = ui->tableWidget->item(row,1)->text();//取出当前行第1列内容
                checkedInfo.removeOne(id);
            }
        }
    });
    return check;
}

AnalyzingConfig::AnalyzingConfig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AnalyzingConfig)
{
    ui->setupUi(this);
    queryfxui=new queryfx();

    queryfxui->jyfxy="全部";
    queryfxui->reagentKitType="全部";
    queryfxui->reagentKitName="全部";
    queryfxui->system="全部";

    QStringList  labels;
    labels <<QStringLiteral("选择") <<QStringLiteral("ID") <<QStringLiteral("基因分析仪") << QStringLiteral("试剂盒类型") << QStringLiteral("试剂盒名称") << QStringLiteral("体系(μl)")<<QStringLiteral("创建时间")<<QStringLiteral("备注");
    ui->tableWidget->setColumnCount(8);
    ui->tableWidget->setHorizontalHeaderLabels(labels);
    ui->tableWidget->resizeColumnsToContents(); //根据内容调整列宽
    ui->tableWidget->setColumnHidden(1, true); // 隐藏第2列
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setStyleSheet("background-color: rgb(235,243,255);");
    QHeaderView* headerView = ui->tableWidget->verticalHeader();
    headerView->setHidden(false); //false 显示行号列  true Hide
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="SELECT Name FROM ItemCode WHERE DicCode=21 and IsDefault=1 ";
    query.exec(sql);
    while (query.next()) {
        if(query.value("Name").toString()=="1"){
            ui->sykg_bt->setText("上样方案(开)");
        }else{
            ui->sykg_bt->setText("上样方案(关)");
        }
    }
}

AnalyzingConfig::~AnalyzingConfig()
{
    delete ui;
}

void AnalyzingConfig::showEvent(QShowEvent *event){
    refl();
    if(doorStatus.get()==0)
    {
        ui->pushButton_9->setText("        打开仓门");
    }
    else
    {
        ui->pushButton_9->setText("        关闭仓门");
    }
}

void AnalyzingConfig::on_SaveBtn_3_clicked()
{
    hhpdui = new hhpd();
    // 获取屏幕的中心点
    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    int centerX = screenGeometry.center().x();
    int centerY = screenGeometry.center().y();
    int labelWidth = hhpdui->sizeHint().width(); // 获取QLabel的建议大小
    int labelHeight = hhpdui->sizeHint().height();
    int labelX = centerX-220;
    int labelY = centerY-200;
    hhpdui->show();
    hhpdui->move(labelX, labelY);
}

void AnalyzingConfig::on_SaveBtn_2_clicked()
{

    QStringList sFilePath;

#ifdef Q_OS_ANDROID

    DialogFileManager dfm(0);
    dfm.exec();
    QString remotePath = dfm.getResult();
    QString localPath = SMBManager::SMB2Local(remotePath);
    if(remotePath == ""){
        return;
    }
    SMBManager::I().downloadFile(remotePath, localPath);
    sFilePath.append(localPath);

#else
    QFileDialog *fDialog=new QFileDialog(this,"file dlg","/home","Excel files(*.xlsx)");
    if(fDialog->exec()==QFileDialog::Accepted)
    {
        sFilePath= fDialog->selectedFiles();
    }
#endif
    if(sFilePath.length()>0){
        QXlsx::Document xlsx(sFilePath[0]);
        QStringList sheetList = xlsx.sheetNames();

        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        db.transaction();
        for (int i=0;i<sheetList.count();i++) {
            xlsx.selectSheet(sheetList[i]);
            QXlsx::Worksheet *worksheet = xlsx.currentWorksheet();

            QString jyfxyq = worksheet->read("A3").toString();//基因分析仪
            QString reagentKitType =worksheet->read("B3").toString();//试剂盒类型
            QString reagentKitName =worksheet->read("C3").toString();//试剂盒名称
            QString system =worksheet->read("D3").toString();//体系
            QString memo =worksheet->read("E3").toString();//备注

            QString sql=QString("Select Name From ItemCode Where DicCode=(Select Code From ItemCode Where Name='%1')").arg(reagentKitType);
            query.exec(sql);
            bool canImport=false;
            while (query.next()) {
                if(query.value("Name").toString()==reagentKitName){
                    canImport=true;
                }
            }

            if(canImport){
                QString configGuid="";

                int num;
                sql=QString("Select Count(*) as Num From DataAnalyseConfig Where GeneticAnalysers='%1' and ReagentKitType='%2' and ReagentKitName='%3' and System='%4' ").arg(jyfxyq,reagentKitType,reagentKitName,system);
                query.exec(sql);
                while (query.next()) {
                    num=query.value("Num").toInt();
                }

                if(num>0)
                {
                    QString oldModelGuid;
                    sql=QString("Select ID,ModelGuid From DataAnalyseConfig Where GeneticAnalysers='%1' and ReagentKitType='%2' and ReagentKitName='%3' and System='%4' ").arg(jyfxyq,reagentKitType,reagentKitName,system);
                    query.exec(sql);
                    while (query.next())
                    {
                        configGuid=query.value("ID").toString();
                        oldModelGuid=query.value("ModelGuid").toString();
                    }

                    sql=QString("Delete From ModelConfigurationNormal Where ID='%1'").arg(oldModelGuid);
                    query.exec(sql);

                    sql=QString("Delete From ModelConfigurationY Where ID='%1'").arg(oldModelGuid);
                    query.exec(sql);

                    sql=QString("Delete From ModelConfigurationMini Where ID='%1'").arg(oldModelGuid);
                    query.exec(sql);
                }
                else
                {
                    configGuid =common->GetGuid();
                }

                if(reagentKitType=="常STR"){
                    QString modelGuid=common->GetGuid();
                    sql=QString("Insert into ModelConfigurationNormal Values('%1','%2','%3','%4')").arg(modelGuid,"0","检测方案",worksheet->read("F3").toString());
                    query.exec(sql);
                    sql=QString("Insert into ModelConfigurationNormal Values('%1','%2','%3','%4')").arg(modelGuid,"0","备注",worksheet->read("G3").toString());
                    query.exec(sql);

                    for (int m=5;m<26;m++) {
                        sql=QString("Insert into ModelConfigurationNormal Values('%1','%2','%3','%4')").arg(modelGuid,"1",worksheet->read("A"+QString::number(m)).toString(),worksheet->read("B"+QString::number(m)).toString());
                        query.exec(sql);
                    }

                    QString createTime=common->GetDateTimeStr();
                    sql=QString("Insert or replace into DataAnalyseConfig Values('%1','%2','%3','%4','%5','%6','%7','%8')").arg(configGuid,jyfxyq,reagentKitType,reagentKitName,system,modelGuid,createTime,memo);
                    query.exec(sql);
                }
                else if(reagentKitType=="Y-STR"){

                    QString modelGuid=common->GetGuid();

                    for (int m=5;m<21;m++) {
                        sql=QString("Insert into ModelConfigurationY Values('%1','%2','%3')").arg(modelGuid,worksheet->read("A"+QString::number(m)).toString(),worksheet->read("B"+QString::number(m)).toString());
                        query.exec(sql);
                    }

                    QString createTime=common->GetDateTimeStr();
                    sql=QString("Insert or replace into DataAnalyseConfig Values('%1','%2','%3','%4','%5','%6','%7','%8')").arg(configGuid,jyfxyq,reagentKitType,reagentKitName,system,modelGuid,createTime,memo);

                    query.exec(sql);

                }else if(reagentKitType=="mini-STR"){

                    QString modelGuid=common->GetGuid();

                    for (int m=5;m<19;m++) {
                        sql=QString("Insert into ModelConfigurationMini Values('%1','%2','%3')").arg(modelGuid,worksheet->read("A"+QString::number(m)).toString(),worksheet->read("B"+QString::number(m)).toString());
                        query.exec(sql);
                    }

                    QString createTime=common->GetDateTimeStr();
                    sql=QString("Insert or replace into DataAnalyseConfig Values('%1','%2','%3','%4','%5','%6','%7','%8')").arg(configGuid,jyfxyq,reagentKitType,reagentKitName,system,modelGuid,createTime,memo);
                    query.exec(sql);
                }
            }
        }
        db.commit();
        refl();
    }
#ifdef Q_OS_ANDROID
    if(SMBManager::isSMBPath(remotePath)){
        SMBManager::I().uploadFile(remotePath, localPath);
    }
#endif

}

void AnalyzingConfig::on_pushButton_clicked()
{
    // 获取屏幕的中心点
    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    int centerX = screenGeometry.center().x();
    int centerY = screenGeometry.center().y();
    int labelWidth = queryfxui->sizeHint().width(); // 获取QLabel的建议大小
    int labelHeight = queryfxui->sizeHint().height();
    int labelX = centerX-220;
    int labelY = centerY-204;
    queryfxui->show();
    queryfxui->move(labelX, labelY);
    connect(queryfxui->ui->pushButton_3,SIGNAL(clicked()),this,SLOT(refl()));// 曲线表格刷新
}

void AnalyzingConfig::refl(){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);


    QString querySql;
    if(!queryfxui->jyfxy.contains("全部"))
    {
        QList<QString> queryList=queryfxui->jyfxy.split(',');
        QString queryInfo;
        for (int i=0;i<queryList.length();i++)
        {
            queryInfo+="'"+queryList[i]+"',";
        }
        queryInfo = queryInfo.left(queryInfo.length()-1);

        querySql+=QString("and GeneticAnalysers in (%1) ").arg(queryInfo);
    }

    if(!queryfxui->reagentKitType.contains("全部"))
    {
        QList<QString> queryList=queryfxui->reagentKitType.split(',');
        QString queryInfo;
        for (int i=0;i<queryList.length();i++)
        {
            queryInfo+="'"+queryList[i]+"',";
        }
        queryInfo = queryInfo.left(queryInfo.length()-1);


        querySql+=QString("and ReagentKitType in (%1) ").arg(queryInfo);

    }

    if(!queryfxui->reagentKitName.contains("全部"))
    {
        QList<QString> queryList=queryfxui->reagentKitName.split(',');
        QString queryInfo;
        for (int i=0;i<queryList.length();i++)
        {
            queryInfo+="'"+queryList[i]+"',";
        }
        queryInfo = queryInfo.left(queryInfo.length()-1);

        querySql+=QString("and ReagentKitName in (%1) ").arg(queryInfo);

    }

    if(!queryfxui->system.contains("全部"))
    {
        QList<QString> queryList=queryfxui->system.split(',');
        QString queryInfo;
        for (int i=0;i<queryList.length();i++)
        {
            queryInfo+="'"+queryList[i]+"',";
        }
        queryInfo = queryInfo.left(queryInfo.length()-1);

        querySql+=QString("and System in (%1) ").arg(queryInfo);

    }

    if(!queryfxui->memo.isNull()&& !queryfxui->memo.isEmpty())
    {
        querySql+=QString("and memo= '%1' ").arg(queryfxui->memo);
    }

    QString sql=QString("Select * From DataAnalyseConfig "
                        "Where 1=1 %1 ").arg(querySql);
    query.exec(sql);

    ui->tableWidget->setRowCount(0);
    int rowNum=0;
    QList<QString> lableList;
    lableList<<""<<"ID"<<"GeneticAnalysers"<<"ReagentKitType"<<"ReagentKitName"<<"System"<<"CreateTime"<<"Memo";
    while (query.next())
    {
        ui->tableWidget->insertRow(rowNum);
        ui->tableWidget->setRowHeight(rowNum, 50);
        setCheckBox(ui->tableWidget,rowNum,0,false);

        for (int col = 1; col < lableList.length(); col++) {
            QTableWidgetItem *item = new QTableWidgetItem(query.value(lableList[col]).toString());
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
            ui->tableWidget->setItem(rowNum, col, item);
            ui->tableWidget->item(rowNum,col)->setTextAlignment(Qt::AlignCenter);

        }
        rowNum++;
    }
}

void AnalyzingConfig::on_returnBtn_clicked()
{
    this->close();
    emit changeSetUpTotalWindow();
}

void AnalyzingConfig::on_pushButton_9_clicked()
{
    if(doorStatus.get()==0)
    {
        doorStatus.set(1);
        ui->pushButton_9->setText("        关闭仓门");
    }
    else
    {
        doorStatus.set(0);
        ui->pushButton_9->setText("        打开仓门");
    }
}

void AnalyzingConfig::on_SaveBtn_clicked()
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    for (int i=0;i<checkedInfo.length();i++) {
        QString sql=QString("Delete From ModelConfigurationNormal where id=(Select ModelGuid From DataAnalyseConfig where ID='%1')").arg(checkedInfo[i]);
        query.exec(sql);

        sql=QString("Delete From ModelConfigurationMini where id=(Select ModelGuid From DataAnalyseConfig where ID='%1')").arg(checkedInfo[i]);
        query.exec(sql);

        sql=QString("Delete From ModelConfigurationY where id=(Select ModelGuid From DataAnalyseConfig where ID='%1')").arg(checkedInfo[i]);
        query.exec(sql);

        sql=QString("Delete From DataAnalyseConfig where Id='%1'").arg(checkedInfo[i]);
        query.exec(sql);
    }
    checkedInfo.clear();
    refl();
}

void AnalyzingConfig::on_pushButton_2_clicked()
{
    editPassWord *editW=new editPassWord();
    // 获取屏幕的中心点
    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    int centerX = screenGeometry.center().x();
    int centerY = screenGeometry.center().y();
    int labelWidth = editW->sizeHint().width(); // 获取QLabel的建议大小
    int labelHeight = editW->sizeHint().height();
    int labelX = centerX-220;
    int labelY = centerY-130;
    editW->show();
    editW->move(labelX, labelY);
}

// 上样方案开关
void AnalyzingConfig::on_sykg_bt_clicked()
{
    QString sykg;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="SELECT Name FROM ItemCode WHERE DicCode=21 and IsDefault=1 ";
    query.exec(sql);
    while (query.next()) {
        sykg=query.value("Name").toString();
    }
    if(sykg=="1"){
        ui->sykg_bt->setText("上样方案(关)");
        sql="UPDATE ItemCode SET Name ='0' WHERE DicCode='21'";
        query.exec(sql);
    }else{
        ui->sykg_bt->setText("上样方案(开)");
        sql="UPDATE ItemCode SET Name ='1' WHERE DicCode='21'";
        query.exec(sql);
    }
}
